{% extends "base.html" %}

{% block title %}{{ page_title }} - 乒乓球培训管理系统{% endblock %}

{% block extra_css %}
<style>
    :root {
        --primary-color: #667eea;
        --secondary-color: #764ba2;
        --success-color: #10b981;
        --warning-color: #f59e0b;
        --danger-color: #ef4444;
        --info-color: #3b82f6;
        --gray-50: #f9fafb;
        --gray-100: #f3f4f6;
        --gray-200: #e5e7eb;
        --gray-500: #6b7280;
        --gray-600: #4b5563;
        --gray-700: #374151;
        --gray-900: #111827;
        --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        --border-radius: 8px;
    }

    .page-header {
        background: white;
        border-radius: var(--border-radius);
        padding: 2rem;
        margin-bottom: 2rem;
        box-shadow: var(--shadow);
        border: 1px solid var(--gray-200);
    }

    .page-title {
        font-size: 1.75rem;
        font-weight: 700;
        color: var(--gray-900);
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .page-title i {
        color: var(--primary-color);
    }

    .breadcrumb {
        margin: 0.5rem 0 0 0;
        background: none;
        padding: 0;
    }

    .breadcrumb-item a {
        color: var(--gray-600);
        text-decoration: none;
    }

    .breadcrumb-item a:hover {
        color: var(--primary-color);
    }

    /* 简化统计卡片 */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        box-shadow: var(--shadow);
        transition: all 0.2s ease;
    }

    .stat-card:hover {
        box-shadow: var(--shadow-md);
        transform: translateY(-1px);
    }

    .stat-header {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 0.75rem;
    }

    .stat-icon {
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.125rem;
        color: white;
    }

    .stat-icon.primary { background: var(--primary-color); }
    .stat-icon.success { background: var(--success-color); }
    .stat-icon.warning { background: var(--warning-color); }
    .stat-icon.info { background: var(--info-color); }

    .stat-label {
        font-size: 0.875rem;
        color: var(--gray-600);
        font-weight: 500;
    }

    .stat-value {
        font-size: 1.875rem;
        font-weight: 700;
        color: var(--gray-900);
        line-height: 1;
    }

    /* 简化筛选器 */
    .filters-card {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: var(--shadow);
    }

    .filter-grid {
        display: grid;
        grid-template-columns: 2fr 1fr 1fr 1fr auto;
        gap: 1rem;
        align-items: end;
    }

    .form-label {
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
    }

    .form-control, .form-select {
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 0.5rem 0.75rem;
        font-size: 0.9rem;
        transition: all 0.2s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgb(102, 126, 234, 0.1);
        outline: none;
    }

    .search-input-group {
        position: relative;
    }

    .search-input-group .input-icon {
        position: absolute;
        left: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
        color: var(--gray-500);
        z-index: 5;
    }

    .search-input-group .form-control {
        padding-left: 2.5rem;
    }

    /* 简化表格 */
    .accounts-table {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        box-shadow: var(--shadow);
        overflow: hidden;
    }

    .table {
        margin: 0;
    }

    .table thead th {
        background: var(--gray-50);
        border-bottom: 2px solid var(--gray-200);
        font-weight: 600;
        color: var(--gray-700);
        font-size: 0.875rem;
        padding: 1rem 0.75rem;
    }

    .table td {
        padding: 1rem 0.75rem;
        vertical-align: middle;
        border-bottom: 1px solid var(--gray-100);
        font-size: 0.9rem;
    }

    .table tbody tr:hover {
        background: var(--gray-50);
    }

    /* 用户信息卡片 */
    .user-info {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .user-avatar {
        width: 2.5rem;
        height: 2.5rem;
        background: var(--gray-100);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--gray-500);
        font-size: 1rem;
        flex-shrink: 0;
    }

    .user-details h6 {
        margin: 0;
        font-size: 0.95rem;
        font-weight: 600;
        color: var(--gray-900);
    }

    .user-details .text-muted {
        font-size: 0.8rem;
        color: var(--gray-500);
        margin: 0;
    }

    /* 余额显示 */
    .balance-amount {
        font-size: 1.1rem;
        font-weight: 700;
        color: var(--success-color);
    }

    /* 状态标签 */
    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.25rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.8rem;
        font-weight: 500;
        background: rgb(16, 185, 129, 0.1);
        color: var(--success-color);
        border: 1px solid rgb(16, 185, 129, 0.2);
    }

    /* 操作按钮 */
    .action-buttons {
        display: flex;
        gap: 0.5rem;
    }

    .btn {
        border-radius: var(--border-radius);
        font-size: 0.8rem;
        font-weight: 500;
        padding: 0.375rem 0.75rem;
        border: 1px solid transparent;
        transition: all 0.2s ease;
    }

    .btn-sm {
        padding: 0.25rem 0.625rem;
        font-size: 0.75rem;
    }

    .btn-primary {
        background: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .btn-primary:hover {
        background: #5a6fd8;
        border-color: #5a6fd8;
        color: white;
    }

    .btn-success {
        background: var(--success-color);
        border-color: var(--success-color);
        color: white;
    }

    .btn-success:hover {
        background: #059669;
        border-color: #059669;
        color: white;
    }

    .btn-warning {
        background: var(--warning-color);
        border-color: var(--warning-color);
        color: white;
    }

    .btn-warning:hover {
        background: #d97706;
        border-color: #d97706;
        color: white;
    }

    .btn-outline-secondary {
        color: var(--gray-600);
        border-color: var(--gray-300);
    }

    .btn-outline-secondary:hover {
        background: var(--gray-100);
        border-color: var(--gray-400);
        color: var(--gray-700);
    }

    /* 空状态 */
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        color: var(--gray-500);
    }

    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    .empty-state h5 {
        color: var(--gray-700);
        margin-bottom: 0.5rem;
    }

    /* 分页 */
    .pagination-wrapper {
        background: white;
        border: 1px solid var(--gray-200);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-top: 2rem;
        box-shadow: var(--shadow);
    }

    .pagination {
        margin: 0;
        justify-content: center;
    }

    .page-link {
        color: var(--gray-600);
        border: 1px solid var(--gray-200);
        padding: 0.5rem 0.75rem;
        font-size: 0.875rem;
    }

    .page-link:hover {
        color: var(--primary-color);
        background: var(--gray-50);
        border-color: var(--gray-300);
    }

    .page-item.active .page-link {
        background: var(--primary-color);
        border-color: var(--primary-color);
        color: white;
    }

    .pagination-info {
        text-align: center;
        margin-top: 1rem;
        font-size: 0.875rem;
        color: var(--gray-500);
    }

    /* 响应式 */
    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: 1fr;
        }

        .filter-grid {
            grid-template-columns: 1fr;
            gap: 1rem;
        }

        .table-responsive {
            font-size: 0.8rem;
        }

        .action-buttons {
            flex-direction: column;
            gap: 0.25rem;
        }

        .user-info {
            flex-direction: column;
            align-items: flex-start;
            gap: 0.5rem;
        }
    }

    /* 搜索高亮 */
    .search-highlight {
        background: #fff3cd;
        padding: 0.1rem 0.2rem;
        border-radius: 3px;
        font-weight: 600;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">
            <i class="bi bi-people"></i>
            用户账户管理
        </h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item">
                    <a href="{{ url_for('dashboard.index') }}">控制台</a>
                </li>
                <li class="breadcrumb-item active">用户账户</li>
            </ol>
        </nav>
    </div>

    <!-- 统计概览 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-header">
                <div class="stat-icon primary">
                    <i class="bi bi-people"></i>
                </div>
                <div class="stat-label">总用户数</div>
            </div>
            <div class="stat-value">{{ stats.total_users or 0 }}</div>
        </div>

        <div class="stat-card">
            <div class="stat-header">
                <div class="stat-icon success">
                    <i class="bi bi-person-check"></i>
                </div>
                <div class="stat-label">活跃账户</div>
            </div>
            <div class="stat-value">{{ stats.active_accounts or 0 }}</div>
        </div>

        <div class="stat-card">
            <div class="stat-header">
                <div class="stat-icon info">
                    <i class="bi bi-wallet2"></i>
                </div>
                <div class="stat-label">总余额</div>
            </div>
            <div class="stat-value">¥{{ "%.2f"|format(stats.total_balance or 0) }}</div>
        </div>

        <div class="stat-card">
            <div class="stat-header">
                <div class="stat-icon warning">
                    <i class="bi bi-arrow-up-circle"></i>
                </div>
                <div class="stat-label">今日充值</div>
            </div>
            <div class="stat-value">¥{{ "%.2f"|format(stats.today_recharge or 0) }}</div>
        </div>
    </div>

    <!-- 筛选器 -->
    <div class="filters-card">
        <form method="GET" id="filterForm">
            <div class="filter-grid">
                <div>
                    <label class="form-label">搜索用户</label>
                    <div class="search-input-group">
                        <i class="bi bi-search input-icon"></i>
                        <input type="text" class="form-control" name="search"
                               value="{{ search }}" placeholder="用户名、姓名或手机号">
                    </div>
                </div>

                <div>
                    <label class="form-label">余额筛选</label>
                    <select class="form-select" name="balance_filter">
                        <option value="">全部余额</option>
                        <option value="zero" {{ 'selected' if balance_filter == 'zero' }}>零余额</option>
                        <option value="low" {{ 'selected' if balance_filter == 'low' }}>低余额(&lt;100)</option>
                        <option value="high" {{ 'selected' if balance_filter == 'high' }}>高余额(&gt;1000)</option>
                    </select>
                </div>

                <div>
                    <label class="form-label">每页条数</label>
                    <select class="form-select" name="per_page">
                        <option value="20" {{ 'selected' if request.args.get('per_page', '20') == '20' }}>有2线服务 20条</option>
                        <option value="50" {{ 'selected' if request.args.get('per_page') == '50' }}>50条</option>
                        <option value="100" {{ 'selected' if request.args.get('per_page') == '100' }}>100条</option>
                    </select>
                </div>

                <div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i>
                        搜索
                    </button>
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-3">
                <a href="{{ url_for('admin_accounts.list_accounts') }}"
                   class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-arrow-clockwise"></i>
                    重置筛选
                </a>

                <div class="text-muted" style="font-size: 0.875rem;">
                    找到 <strong>{{ pagination.total if pagination else 0 }}</strong> 个用户
                </div>
            </div>
        </form>
    </div>

    <!-- 账户列表 -->
    <div class="accounts-table">
        {% if accounts %}
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th width="35%">用户信息</th>
                        <th width="15%">账户余额</th>
                        <th width="15%">最后交易</th>
                        <th width="35%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for account in accounts %}
                    <tr>
                        <td>
                            <div class="user-info">
                                <div class="user-avatar">
                                    <i class="bi bi-person"></i>
                                </div>
                                <div class="user-details">
                                    <h6>
                                        {% if search and search in (account.real_name or '') %}
                                            {{ account.real_name|replace(search, '<span class="search-highlight">' + search + '</span>')|safe }}
                                        {% else %}
                                            {{ account.real_name or '未设置姓名' }}
                                        {% endif %}
                                    </h6>
                                    <div class="text-muted">
                                        @{{ account.username }}
                                        {% if account.phone %}
                                        · {{ account.phone }}
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="balance-amount">
                                ¥{{ "%.2f"|format(account.balance or 0) }}
                            </div>
                        </td>
                        <td>
                            {% if account.account_updated_at %}
                                <div>{{ account.account_updated_at.strftime('%m-%d %H:%M') }}</div>
                                <small class="text-muted">
                                    {{ (now() - account.account_updated_at).days }}天前
                                </small>
                            {% else %}
                                <span class="text-muted">无记录</span>
                            {% endif %}
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="{{ url_for('admin_accounts.account_detail', user_id=account.id) }}"
                                   class="btn btn-primary btn-sm">
                                    <i class="bi bi-eye"></i>
                                    详情
                                </a>
                                <a href="{{ url_for('admin_accounts.offline_recharge', user_id=account.id) }}"
                                   class="btn btn-success btn-sm">
                                    <i class="bi bi-plus-lg"></i>
                                    充值
                                </a>
                                <button type="button" class="btn btn-warning btn-sm"
                                        onclick="showBalanceOperation({{ account.id }}, '{{ account.username }}')">
                                    <i class="bi bi-gear"></i>
                                    调整
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="empty-state">
            <i class="bi bi-people"></i>
            <h5>暂无用户账户</h5>
            <p>当前筛选条件下没有找到用户账户</p>
            <a href="{{ url_for('admin_accounts.list_accounts') }}" class="btn btn-primary">
                <i class="bi bi-arrow-clockwise"></i>
                重置筛选
            </a>
        </div>
        {% endif %}
    </div>

    <!-- 分页 -->
    {% if pagination and pagination.pages > 1 %}
    <div class="pagination-wrapper">
        <nav aria-label="账户列表分页">
            <ul class="pagination">
                <!-- 首页 -->
                <li class="page-item {{ 'disabled' if pagination.page == 1 }}">
                    <a class="page-link" href="{{ url_for('admin_accounts.list_accounts', page=1, **request.args) }}">
                        <i class="bi bi-chevron-double-left"></i>
                    </a>
                </li>

                <!-- 上一页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_prev }}">
                    <a class="page-link" href="{{ url_for('admin_accounts.list_accounts', page=pagination.prev_num, **request.args) if pagination.has_prev }}">
                        <i class="bi bi-chevron-left"></i>
                    </a>
                </li>

                <!-- 页码 -->
                {% for page_num in pagination.iter_pages() %}
                    {% if page_num %}
                        {% if page_num != pagination.page %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('admin_accounts.list_accounts', page=page_num, **request.args) }}">
                                {{ page_num }}
                            </a>
                        </li>
                        {% else %}
                        <li class="page-item active">
                            <span class="page-link">{{ page_num }}</span>
                        </li>
                        {% endif %}
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link">…</span>
                    </li>
                    {% endif %}
                {% endfor %}

                <!-- 下一页 -->
                <li class="page-item {{ 'disabled' if not pagination.has_next }}">
                    <a class="page-link" href="{{ url_for('admin_accounts.list_accounts', page=pagination.next_num, **request.args) if pagination.has_next }}">
                        <i class="bi bi-chevron-right"></i>
                    </a>
                </li>

                <!-- 末页 -->
                <li class="page-item {{ 'disabled' if pagination.page == pagination.pages }}">
                    <a class="page-link" href="{{ url_for('admin_accounts.list_accounts', page=pagination.pages, **request.args) }}">
                        <i class="bi bi-chevron-double-right"></i>
                    </a>
                </li>
            </ul>
        </nav>

        <div class="pagination-info">
            显示第 {{ (pagination.page - 1) * pagination.per_page + 1 }} -
            {{ pagination.page * pagination.per_page if pagination.page * pagination.per_page < pagination.total else pagination.total }} 条，
            共 {{ pagination.total }} 条记录
        </div>
    </div>
    {% endif %}
</div>

<!-- 余额操作模态框 -->
<div class="modal fade" id="balanceOperationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-gear me-2"></i>账户余额操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="balanceOperationForm">
                <div class="modal-body">
                    <div class="alert alert-info">
                        <strong>用户:</strong> <span id="targetUsername"></span>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">操作类型</label>
                        <select class="form-select" name="operation_type" required>
                            <option value="">请选择操作类型</option>
                            <option value="adjust">余额调整（设置为指定金额）</option>
                            <option value="recharge">余额充值（在现有基础上增加）</option>
                            <option value="consume">余额扣减（从现有余额中扣除）</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">操作金额</label>
                        <div class="input-group">
                            <span class="input-group-text">¥</span>
                            <input type="number" class="form-control" name="amount"
                                   min="0.01" step="0.01" required>
                        </div>
                        <small class="form-text text-muted" id="amountHelpText">
                            请先选择操作类型查看具体说明
                        </small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">操作原因</label>
                        <textarea class="form-control" name="reason" rows="3"
                                  placeholder="请详细说明操作原因..." required></textarea>
                    </div>

                    <input type="hidden" name="user_id" id="operationUserId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-lg me-2"></i>确认操作
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 自动提交筛选表单 - 只针对筛选表单中的select
    const filterForm = document.getElementById('filterForm');
    if (filterForm) {
        const filterSelects = filterForm.querySelectorAll('.form-select');
        const searchInput = filterForm.querySelector('input[name="search"]');

        filterSelects.forEach(select => {
            select.addEventListener('change', function() {
                filterForm.submit();
            });
        });

        // 搜索输入防抖
        let searchTimeout;
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                const value = this.value.trim();
                searchTimeout = setTimeout(() => {
                    if (value.length === 0 || value.length >= 2) {
                        filterForm.submit();
                    }
                }, 500);
            });
        }
    }

    // 余额操作表单提交
    const balanceForm = document.getElementById('balanceOperationForm');
    if (balanceForm) {
        balanceForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitBalanceOperation();
        });

        // 监听操作类型变化 - 只针对模态框内的select
        const operationTypeSelect = balanceForm.querySelector('select[name="operation_type"]');
        if (operationTypeSelect) {
            operationTypeSelect.addEventListener('change', function() {
                updateAmountHelpText(this.value);
            });
        }
    }
});

// 更新金额输入帮助文本
function updateAmountHelpText(operationType) {
    const helpText = document.getElementById('amountHelpText');
    if (!helpText) return;

    switch (operationType) {
        case 'adjust':
            helpText.textContent = '余额调整：输入调整后的目标余额（将将用户余额设置为此金额）';
            break;
        case 'recharge':
            helpText.textContent = '余额充值：输入充值金额（将在用户现有余额基础上增加此金额）';
            break;
        case 'consume':
            helpText.textContent = '余额扣减：输入扣减金额（将从用户现有余额中扣除此金额）';
            break;
        default:
            helpText.textContent = '请先选择操作类型查看具体说明';
    }
}

// 显示余额操作模态框
function showBalanceOperation(userId, username) {
    // 设置用户信息
    document.getElementById('targetUsername').textContent = username;
    document.getElementById('operationUserId').value = userId;

    // 重置表单到初始状态
    const form = document.getElementById('balanceOperationForm');
    if (form) {
        form.reset(); // 重置所有表单字段

        // 确保隐藏字段仍然有正确的值
        document.getElementById('operationUserId').value = userId;

        // 清除所有错误状态
        form.querySelectorAll('.is-invalid').forEach(element => {
            element.classList.remove('is-invalid');
        });

        // 清除所有错误信息
        form.querySelectorAll('.invalid-feedback').forEach(element => {
            element.remove();
        });

        // 重置帮助文本
        updateAmountHelpText('');
    }

    const modal = new bootstrap.Modal(document.getElementById('balanceOperationModal'));
    modal.show();
}

// 提交余额操作
function submitBalanceOperation() {
    const form = document.getElementById('balanceOperationForm');
    const formData = new FormData(form);

    // 验证表单完整性
    const operationType = formData.get('operation_type');
    const amount = formData.get('amount');
    const reason = formData.get('reason');
    const userId = formData.get('user_id');

    // 基本字段验证
    if (!operationType) {
        showAlert('请选择操作类型', 'warning');
        return;
    }

    if (!amount || isNaN(amount) || parseFloat(amount) <= 0) {
        showAlert('请输入有效的操作金额', 'warning');
        return;
    }

    if (!reason || reason.trim().length < 5) {
        showAlert('请输入详细的操作原因（至少5个字符）', 'warning');
        return;
    }

    if (!userId) {
        showAlert('用户信息错误，请重新打开操作窗口', 'danger');
        return;
    }

    // 生成确认信息
    const username = document.getElementById('targetUsername').textContent;
    let operationName = '';
    let operationDescription = '';

    switch (operationType) {
        case 'adjust':
            operationName = '余额调整';
            operationDescription = `将余额设置为 ¥${parseFloat(amount).toFixed(2)}`;
            break;
        case 'recharge':
            operationName = '余额充值';
            operationDescription = `增加余额 ¥${parseFloat(amount).toFixed(2)}`;
            break;
        case 'consume':
            operationName = '余额扣减';
            operationDescription = `扣减余额 ¥${parseFloat(amount).toFixed(2)}`;
            break;
        default:
            operationName = operationType;
            operationDescription = `操作金额 ¥${parseFloat(amount).toFixed(2)}`;
    }

    const confirmMessage = `确认对用户 "${username}" 执行${operationName}操作？\n\n${operationDescription}\n操作原因：${reason}\n\n此操作将被记录在系统日志中，请确认无误后继续。`;

    if (!confirm(confirmMessage)) {
        return;
    }

    // 禁用提交按钮，防止重复提交
    const submitButton = form.querySelector('button[type="submit"]');
    if (submitButton) {
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>处理中...';
    }

    fetch('{{ url_for("admin_accounts.api_balance_operation") }}', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('balanceOperationModal')).hide();
            showAlert('操作成功：' + (data.message || `${operationName}已完成`), 'success');

            // 1.5秒后刷新页面
            setTimeout(() => {
                location.reload();
            }, 1500);
        } else {
            showAlert('操作失败：' + (data.error || '未知错误'), 'danger');
        }
    })
    .catch(error => {
        console.error('余额操作失败:', error);
        showAlert('操作失败，请检查网络连接后重试', 'danger');
    })
    .finally(() => {
        // 恢复提交按钮状态
        if (submitButton) {
            submitButton.disabled = false;
            submitButton.innerHTML = '<i class="bi bi-check-lg me-2"></i>确认操作';
        }
    });
}

// 显示提示信息
function showAlert(message, type = 'info') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(alertDiv);

    // 3秒后自动隐藏
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}
</script>
{% endblock %}